<template>
  <view>
    <u-sticky bgColor="#fff">
      <!--      <u-tabs :list="tabsList"-->
      <!--              :current="tabsCurrent"-->
      <!--              :is-scroll="false"-->
      <!--              @click="tabsClick"-->
      <!--              @change="tabsChange"></u-tabs>-->

      <view class="flex-box flex-wrap">
        <view class="check" v-for="(item,index) in tabsList" :key="index"
              :style="[{'background':actives == index?activeBgColor:bgColor,'color':actives == index?activeTextColor:color},btnStyle]"
              @click="checkBtn(index,item)">
          <text class="texts" :style="{'fontSize':fontSize}">{{ item[defaultProps.name] }}</text>
        </view>

        <view
            style="justify-content: center;align-items:center;margin-right: 5px;display: flex;color: green;margin-left: 15px">

          <view style="display: flex;border: 1px solid #000;border-radius:25px;" hover-class="click"
                v-if="showPublishDyAtlasButton">
            <view style="margin-left: 5px;margin-top: 5px">
              <u-icon size="40" name="https://cdn.uviewui.com/uview/example/button.png"></u-icon>
            </view>
            <view style="margin-right: 10px;margin-left: 5px;margin-top: 5px" @click="publishDyAtlas">
              发布抖音图集
            </view>
          </view>


        </view>
      </view>
    </u-sticky>

    <view v-if="tabsCurrent === 0">
      <view v-if="list.length>0">
        <uni-list :border="true" v-for="(item,index) in list" :key="index">
          <uni-list-item link @click="showModal(item)" :title="item.publishGoodsName" :note="item.publishMemberName"
                         :thumb="item.videoUrl+'?'+globalImageProcessingSuffix"
                         thumb-size="lg" :rightText="item.addTime | time()" style="line-height: 30px"></uni-list-item>
        </uni-list>
        <uni-load-more :showIcon="true" :showText="true" :status="loadStatus"
                       v-if="list.length>0&&isMytrends&&total>pageSize"></uni-load-more>
      </view>
      <no-data :list="list" v-else></no-data>


    </view>

    <view v-if="tabsCurrent === 1">

      <view v-if="list.length>0">
        <uni-list :border="true" v-for="(item,index) in list" :key="index">
          <uni-list-item link @click="showModal(item)" :title="item.publishGoodsName" :note="item.publishMemberName"
                         :thumb="item.imgUrl+'?'+globalImageProcessingSuffix"
                         thumb-size="lg" :rightText="item.addTime | time()" style="line-height: 30px"></uni-list-item>
        </uni-list>
        <uni-load-more :showIcon="true" :showText="true" :status="loadStatus"
                       v-if="list.length>0&&isMytrends&&total>pageSize"></uni-load-more>

      </view>
      <no-data :list="list" v-else></no-data>

    </view>

    <u-modal v-model="visible" confirm-text="关闭" z-index="20" title="详情">

      <u-line-progress :striped="true" :percent="percent" :striped-active="true"
                       v-show="showDownloadingLoading"></u-line-progress>
      <scroll-view scroll-y="true">
        <view style="height: 250px;margin: 10px">
          <u-form style="margin: 10px;">
            <u-form-item label="查看作品" prop="applyNum" label-width="100px" class="uFormItem">
              <u-button size="mini" type="primary" @click="openVideoOrImg(modalData)">查看</u-button>
            </u-form-item>
            <u-form-item label="文案" prop="applyNum" label-width="100px" class="uFormItem">

              <u-read-more :show-height="100" :toggle="true" ref="uReadMore">
                <u-parse :html="modalData.content" @load="parseLoaded"></u-parse>
              </u-read-more>

              <span style="margin-left: 10px;color: green" v-if="modalData.content"
                    @click="copyThis(modalData.content)">复制</span>
            </u-form-item>
            <u-form-item label="发布到抖音" prop="applyNum" label-width="100px" class="uFormItem">
              <u-button size="mini" type="primary" @click="publishToDy(modalData)">发布到抖音</u-button>
            </u-form-item>
            <u-form-item label="挂车链接" prop="applyNum" label-width="100px" class="uFormItem">
              <span>{{ modalData.publishGoodsTrailerLink }}</span> <span style="margin-left: 10px;color: green"
                                                                         v-if="modalData.publishGoodsTrailerLink"
                                                                         @click="copyThis(modalData.publishGoodsTrailerLink)">复制</span>
            </u-form-item>
            <u-form-item label="重新下载" prop="applyNum" label-width="100px" class="uFormItem">
              <u-button size="mini" type="primary" @click="downloadAgain(modalData,1)">重新下载</u-button>
            </u-form-item>
            <u-form-item label="下载人姓名" prop="applyNum" label-width="100px" class="uFormItem">
              {{ modalData.downloadWalkMemberName }}
            </u-form-item>

            <u-form-item label="发布人姓名" prop="applyNum" label-width="100px" class="uFormItem">
              {{ modalData.publishWalkMemberName }}
            </u-form-item>

            <u-form-item label="商品主图" prop="applyNum" label-width="100px" class="uFormItem">
              <u-image @click="openImg(modalData.publishGoodsHeadImg)" :src="modalData.publishGoodsHeadImg" width="50px"
                       height="50px"></u-image>
            </u-form-item>

            <u-form-item label="商品名称" prop="applyNum" label-width="100px" class="uFormItem">
              {{ modalData.publishGoodsName }}
            </u-form-item>
            <u-form-item label="店铺logo" prop="applyNum" label-width="100px" class="uFormItem">
              <u-image @click="openImg(modalData.publishShopHeadImg)" class="userAvatar"
                       :src="modalData.publishShopHeadImg" mode="aspectFill">
                <view slot="error" style="font-size: 24rpx;">
                  <img class="userAvatar" :src="config.app_logo+'?'+globalImageProcessingSuffix" alt=""/>
                </view>

              </u-image>
            </u-form-item>

            <u-form-item label="店铺名称" prop="applyNum" label-width="100px" class="uFormItem">
              {{ modalData.publishShopName }}
            </u-form-item>

            <u-form-item label="下载时间" prop="applyNum" label-width="100px" class="uFormItem">
              {{ modalData.addTime | time() }}
            </u-form-item>
          </u-form>
        </view>

      </scroll-view>

    </u-modal>

    <u-modal title="保存指引" v-model="visibleStep" ref="uModalStep" :show-confirm-button="isShowConfirmButton"
             :show-cancel-button="false" confirm-text="前往保存"
             @confirm="afterStepToSave()">
      <view style="margin-top: 10px">
          <span
              @click="skipStep"
              style="text-decoration: underline;color: green;margin-left: 41%">跳过指引</span>
      </view>

      <view style="margin-top: 10px">
        <u-steps :list="numList" :current="currentStep"></u-steps>
        <view style="display: flex;justify-content: center;align-items: center;">
          <u-button @click="preStep" type="primary" size="mini" v-if="showPreStep">上一步</u-button>
          <u-button @click="nextStep" type="primary" size="mini" v-if="showNextStep">下一步</u-button>
        </view>

      </view>


      <u-image mode="widthFix" width="100%" height="700rpx" :src="stepImage"></u-image>


    </u-modal>
    <u-modal title="视频查看" :show-cancel-button="false" v-model="showVideoModal">
      <view style="margin-left: 17px">
        <video id="myVideo" :src="currentVideoUrl"
               controls></video>
      </view>
    </u-modal>

    <u-modal title="素材发布" :show-cancel-button="false" :showConfirmButton="false" v-model="showPublishDyModal"
             @confirm="toPublishDy()" :asyncClose="true">
      <view style="margin-left: 17px">
        <u-form ref="uForm">
          <u-form-item label="文案">
            <u-input v-model="publishContent"/>
          </u-form-item>
          <u-form-item label="直接发布">
            <u-switch slot="right" v-model="shareToPublish"></u-switch>
          </u-form-item>
          <u-form-item v-if="showLink" label="发布链接">
            <u-button size="mini" type="primary" @click="copyLink">复制链接</u-button>
          </u-form-item>
        </u-form>
        <u-alert-tips v-if="showLink" type="primary" description="请复制发布链接，然后打开手机浏览器粘贴到地址栏进行发布"
                      :desc-style="descStyle" style="margin-top: 10px"></u-alert-tips>

        <view style="display: flex;margin-bottom: 5px;margin-top: 5px">
          <u-button size="mini" type="primary" @click="cancel">取消</u-button>
          <u-button style="margin-left: 10px" size="mini" type="primary" @click="toPublishDy()">发布</u-button>
        </view>
      </view>
    </u-modal>
  </view>

</template>

<script>
import UImage from "uview-ui/components/u-image/u-image"


const API = require('../../utils/api/find.js').default;
const APIDy = require('../../utils/api/douyin.js').default;
const $ = require('../../utils/api.js');
const dateChange = require('../../utils/filter.js');
export default {
  props: {

    isMytrends: {
      type: Boolean,
      default: false
    }
  },
  name: "userTrendsDownload",
  components: {UImage},
  watch: {
    list: {
      handler(newValue, oldValue) {
        this.list = newValue;//父组件updateTime对象改变会触发此函数
      },
      deep: true
    },
  },
  data() {
    return {
      showPublishDyAtlasButton: false,
      showPublishDyAtlas: false,
      color: "black",
      btnStyle: {},
      activeTextColor: "blue",
      activeBgColor: "#64bfc2",
      bgColor: "#a3daa3",
      actives: this.active = 0,
      arr: [],
      select: [],
      defaultProps: {
        name: 'name',
        id: 'id',
      },
      fontSize: "24rpx",


      showLink: false,
      descStyle: {
        color: "blue"
      },
      publishImgUrl: "",
      publishUrl: "",
      publishVideo: '',
      shareToPublish: false,
      publishContent: "",
      showPublishDyModal: false,
      config: {},
      globalImageProcessingSuffix: '',
      currentVideoUrl: "",
      showVideoModal: false,
      showPreStep: false,
      showNextStep: false,
      currentHref: "",
      isShowConfirmButton: false,
      stepImage: "https://img.fscmkjznb.com/static/step1.png",
      currentStep: 0,
      numList: [{
        name: '第一步'
      }, {
        name: '第二步'
      }, {
        name: '第三步'
      }, {
        name: '第四步'
      },],
      visibleStep: false,
      percent: 0,
      showDownloadingLoading: false,
      isXcx: false,
      visible: false,
      pageNum: 0,
      page: 1,
      total: 0,
      pageSize: 10,
      totalPage: 0,
      isLoading: false,  //是否加载中
      loadStatus: "",   //uni-load-more的状态
      list: [],
      tabsList: [{
        name: "短视频素材"
      }, {
        name: '图片素材'
      }],
      tabsCurrent: 0,
      modalData: {}
    }
  },
  computed: {
    typeToName: function () {
      return function (type) {
        if (type === 1) {
          return "短视频"
        } else if (type === 3) {
          return "图片"
        }
      }
    }
  },
  methods: {
    publishDyAtlas() {
      $.go('/pages/user/publishAtlas');
    },
    checkBtn(e, info) {
      this.actives = e;
      info.idx = e;
      this.tabsCurrent = e;

      if (e === 0) {
        this.showPublishDyAtlasButton = false
      } else {
        this.showPublishDyAtlasButton = true
      }

      this.loadStatus = ""
      this.isLoading = false
      this.list = []
      this.page = 1
      this.totalPage = 0
      this.getList();
    },
    parseLoaded() {
      this.$refs.uReadMore.init();
    },
    copyLink() {
      this.copy(this.publishUrl)
    },
    cancel() {
      this.showPublishDyModal = false
    },
    publishToDy(data) {
      this.showLink = false
      this.shareToPublish = false
      this.publishContent = data.content
      this.showPublishDyModal = true
      this.publishVideo = data.videoUrl
      this.publishImgUrl = data.imgUrl

    },
    toPublishDy() {
      let self = this
      let type = ""
      let videoUrl = ""
      let imgUrl = ""
      if (self.tabsCurrent === 0) {
        type = "1"
        videoUrl = self.publishVideo
        imgUrl = ""
      } else {
        type = "2"
        videoUrl = ""
        imgUrl = self.publishImgUrl
      }
      let postData = {
        type: type,
        videoUrl: videoUrl,
        imgUrl: imgUrl,
        title: self.publishContent,
        shareToPublish: self.shareToPublish
      }
      //授权成功后拿openid和电话去登录
      $.ajax({
        url: APIDy.publishTrends,
        data: postData,
        method: 'GET',
        complete(res) {
          if (res.code === 200) {
            self.publishUrl = res.data
            self.showLink = true
          } else {
            uni.showToast({
              title: res.message,
              icon: 'none'
            });
          }
        }
      });
    },
// 定义方法，传入参数为图片链接
    checkImgExists(imgUrl) {
      return new Promise(function (resolve, reject) {
        uni.getImageInfo({
          src: imgUrl,
          success: function (image) {
            resolve(image);
          },
          fail: function (image) {
            reject(image);
          },
        });
      })
    },


    preStep() {
      if (this.currentStep > 0) {
        this.currentStep--
      }
      if (this.currentStep === 0) {
        this.showPreStep = false
        this.showNextStep = true
      } else if (this.currentStep === 3) {
        this.showPreStep = true
        this.showNextStep = false
      } else {
        this.showPreStep = true
        this.showNextStep = true
      }
      if (this.currentStep === 0) {
        this.stepImage = "https://img.fscmkjznb.com/static/step1.png"
      } else if (this.currentStep === 1) {
        this.stepImage = "https://img.fscmkjznb.com/static/step2.png"
      } else if (this.currentStep === 2) {
        this.stepImage = "https://img.fscmkjznb.com/static/step3.png"
      } else if (this.currentStep === 3) {
        this.stepImage = "https://img.fscmkjznb.com/static/step4.png"
      }
    },
    nextStep() {
      if (this.currentStep < 3) {
        this.currentStep++
      }
      if (this.currentStep === 0) {
        this.showPreStep = false
        this.showNextStep = true
      } else if (this.currentStep === 3) {
        this.showPreStep = true
        this.showNextStep = false
      } else {
        this.showPreStep = true
        this.showNextStep = true
      }
      if (this.currentStep === 0) {
        this.stepImage = "https://img.fscmkjznb.com/static/step1.png"
      } else if (this.currentStep === 1) {
        this.stepImage = "https://img.fscmkjznb.com/static/step2.png"
      } else if (this.currentStep === 2) {
        this.stepImage = "https://img.fscmkjznb.com/static/step3.png"
      } else if (this.currentStep === 3) {
        this.stepImage = "https://img.fscmkjznb.com/static/step4.png"
        this.isShowConfirmButton = true
      }


    },

    afterStepToSave() {
      var oA = document.createElement("a");
      oA.download = '素材'; // 设置下载的文件名，默认是'下载'
      oA.href = this.currentHref; //临时路径再保存到本地
      document.body.appendChild(oA);
      oA.click();
      oA.remove(); // 下载之后把创建的元素删除
    },
    skipStep() {
      this.visibleStep = false
      this.afterStepToSave()
    },
    onScrollToLower() {
      console.log("11111111111111")
      if (this.isMytrends) {
        this.refreshData()
      }
    },
    //下拉加载更多
    refreshData() {
      if (this.page < this.totalPage) {
        if (!this.isLoading) {  //此处判断，上锁，防止重复请求
          this.isLoading = true;
          this.page += 1;
          this.loadStatus = "loading";
          let type
          if (this.tabsCurrent === 0) {
            type = 1
          } else {
            type = 3
          }
          this.getList(type);
        }
      }
    },
    openVideoOrImg(data) {
      if (this.tabsCurrent === 0) {
        this.openVideo(data)
      } else {
        this.openImg(data.imgUrl)
      }
    },
    downloadAgain(data) {
      console.log(data)
      let url = ''
      let urlImg = data.imgUrl
      let urlVideo = data.videoUrl
      let type = 0
      if (this.tabsCurrent === 0) {
        type = 1
      } else {
        type = 3
      }
      if (type === 1) {
        url = urlVideo
      } else {
        url = urlImg
      }
      this.toDownload(url, type)
    },
    toDownload(url, type) {
      const self = this
      /*#ifdef MP-WEIXIN*/
      self.isXcx = true
      /*#endif*/
      /*#ifdef H5*/
      self.isXcx = false
      /*#endif*/

      const downloadTask = uni.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({
              title: "视频连接正确",
              icon: "none"
            });
            if (!self.isXcx) {
              //如果是H5 那么弹出下载步骤
              self.currentHref = res.tempFilePath
              self.visibleStep = true
              self.currentStep = 0
              self.isShowConfirmButton = false
              self.showPreStep = false
              self.showNextStep = true
            }


            if (self.isXcx) {
              if (type === 1) {
                uni.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: function () {
                    uni.showToast({
                      title: "保存成功",
                      icon: "none"
                    });
                  },
                  fail: function (e) {
                    uni.showToast({
                      title: "保存失败，请稍后重试:" + e.errMsg,
                      icon: "none"
                    });
                    self.percent = 0
                  }
                });
              } else if (type === 3) {
                uni.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: function () {
                    uni.showToast({
                      title: "保存成功",
                      icon: "none"
                    });

                  },
                  fail: function (e) {
                    uni.showToast({
                      title: "保存失败，请稍后重试",
                      icon: "none"
                    });
                    self.percent = 0
                  }
                });
              }
            }
          }
        }
      });

      downloadTask.onProgressUpdate((res) => {
        self.percent = 0
        self.showDownloadingLoading = true
        self.percent = res.progress

      });
    },
    copyThis(data) {
      this.copy(data)
    },
    openImg(url) {
      uni.previewImage({
        urls: [url], // 需要预览的图片链接列表
      });

    },
    openVideo(data) {
      console.log(this.modalData)
      this.currentVideoUrl = this.modalData.videoUrl
      this.showVideoModal = true
      //如果是下载记录去查看，就不走那么video.nvue中 就不需要去差，直接根据下载记录中的副本信息，显示
      // $.go('/pagesA/find/video?videoInfo=' + JSON.stringify(this.modalData) + "&isShowWaterByOtherPage=" + "1");

      // $.go('/pagesA/find/video?id=' + data.trendsId+ '&onlyOneTrendsId=' + data.trendsId+ '&location=' + 1 + '&isSelf=' + 0 + '&userId=' + ""+"&isShowWaterByOtherPage="+"1");
    },
    showModal(item) {
      this.modalData = item
      this.visible = true
      this.showDownloadingLoading = false
    },
    tabsClick(item) {
      console.log('item', item);
    },
    tabsChange(index) {
      this.tabsCurrent = index;
      this.loadStatus = ""
      this.isLoading = false
      this.list = []
      this.page = 1
      this.totalPage = 0
      this.getList();
    },
    getList() {
      const self = this;
      if (!uni.getStorageSync('token')) {
        self.list = []
      } else {


        let type
        if (self.tabsCurrent === 0) {
          type = 1
        } else {
          type = 3
        }

        if (!this.isMytrends) {
          self.pageSize = 4
        }
        $.ajax({
          url: API.listTrendsDownloadLog,
          data: {
            type: type,
            page: self.page,
            pageSize: self.pageSize
          },
          isAuth: true,
          method: 'GET',
          loading: true,
          success(res) {
            // self.list = res.data.list
            res.data.list.forEach(item => {
              if (type === 1) {
                self.checkImgExists(item.videoUrl + "?" + self.globalImageProcessingSuffix).then(() => {
                }).catch(() => {
                  item.videoUrl = "https://img.fscmkjznb.com/static/noImg.jpeg" + "?" + this.globalImageProcessingSuffix;
                })
              } else if (type === 3) {
                self.checkImgExists(item.imgUrl + "?" + self.globalImageProcessingSuffix).then(() => {
                }).catch(() => {
                  item.imgUrl = "https://img.fscmkjznb.com/static/noImg.jpeg" + "?" + this.globalImageProcessingSuffix;
                })
              }


              self.list.push(item)

            })
            console.log(self.list)
            self.totalPage = res.data.totalPage
            self.pageNum = res.data.pageNum
            self.total = res.data.total
            self.isLoading = false;
            let pageNum = res.data.pageNum;

            if (pageNum == self.totalPage) {
              self.loadStatus = ''
            } else {
              self.loadStatus = 'more'
            }
            self.$emit('stopDownRefresh');
          }
        })
      }
    },
    init() {
      this.list = []
      this.page = 1
      this.getList();
    },
    morePageData() {
      if (this.pageNum < this.totalPage) {
        this.page++
        this.getList()
      }
    },
  },
  created() {
    this.globalImageProcessingSuffix = getApp().globalData.globalImageProcessingSuffix;
    this.config = uni.getStorageSync('config') ? uni.getStorageSync('config') : '';
  },
  onReachBottom() {

  }
}
</script>

<style scoped>
.uFormItem {
  line-height: 15px
}

.userAvatar {
  border-radius: 500%;
  border-style: solid;
  border-width: 2px;
  border-color: #ffffff;
}

.userAvatar {
  width: 38px;
  height: 38px;
}

.flex-wrap {
  flex-wrap: wrap;
}

/* flex横向不居中布局 */
.flex-box {
  display: flex;
  align-items: center;
}

.check {
  min-width: 83px;
  text-align: center;
  height: 50rpx;
  line-height: 50rpx;
  box-sizing: border-box;
  background-color: #f6f6f6;
  color: #666666;
  border-radius: 10rpx;
  margin: 10rpx 10rpx;
}


</style>
